package com.roc.web.action.terminal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.TerminalBrand;
import com.roc.util.constant.TerminalName;
import com.roc.util.constant.TerminalType;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/termSNExchange")
public class TermianlSNExchangeAction extends PaginationBaseAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger = LogManager.getLogger(TermianlSNExchangeAction.class);
	private TermianlSNExchangeSearchCondition searchCondition;
	private List<OrgBean> orgList=new ArrayList<OrgBean>();
	private Operators merchant;
    private String serialNum;
	@Autowired
	IPagenitionService pagenitionService;
	@Autowired
	private IorgService orgService;
	@Autowired
	private ITerminalService terminalService;
	
	@Action(value = "termianlSNExchangeInfoJsp",
			results = { @Result(location = "/pages/terminal/terminalSNExchange.jsp") })
	public String termianlSNExchangeInfoAction() throws Exception {
		org();
		return SUCCESS;
	}
	
	@Action(value = "queryTermSNExchangeInfo", results = { @Result(name = "success", location = "/pages/terminal/terminalSNExchange.jsp")
    })
	//查询可变更终端序列号信息
	public String queryTermSNExchangeInfoAction() throws Exception{
	    merchant = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		if(searchCondition==null){
			searchCondition = (TermianlSNExchangeSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition = new TermianlSNExchangeSearchCondition();
			}
		}
		try {
			org();
			searchCondition.setAgentId(merchant.getId());
			int rows=pagenitionService.countSQL(searchCondition);
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			List<YjPosInfo> posList= new ArrayList<YjPosInfo>();
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator iterator=searchRsList.iterator();
				String value = "";
				while (iterator.hasNext()) {
					Object[] obj= (Object[])iterator.next();
					YjPosInfo pos=new YjPosInfo(); 
					pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));
					pos.setPosBrand(TerminalBrand.valueOfCode(Constance.Null2EmptyTrim(obj[1])).getName());
					pos.setPosType(TerminalType.valueOfCode(Constance.Null2EmptyTrim(obj[2])).getName());
					pos.setPosName(Constance.Null2EmptyTrim(obj[3]));
					pos.setOrgCode(Constance.Null2EmptyTrim(obj[4]));
					value = Constance.Null2EmptyTrim(obj[4]);
					for(OrgBean bean:orgList){
						if(value.equals(bean.getOrg_code())){
							pos.setOrgName(bean.getOrg_name());
						}
					}
					posList.add(pos);
				}
			}
			searchRsList.clear();
			searchRsList.addAll(posList);
			dealWithTheListSpecially(searchRsList);
			getRequest().setAttribute("posList", posList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	
	//终端序列号撤回
	@Action(value = "termianlSNExchange", results = {
			@Result(name = "success",type="redirect", location = "/termSNExchange/termAllotRecallInfoJsp.ct"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String termianlSNExchange() throws Exception{
	    merchant = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
	    List<Long> idList = null;
	    String[] serialNumArray = serialNum.split(",");
	    String context ="撤回绑定终端序列号成功";
	    try{
	    	idList = terminalService.getOpertorsIdsTreeById(merchant.getId());
	    	if(serialNumArray!=null && serialNumArray.length>0){
	    		for(String sn:serialNumArray){
	    			if(sn!=null && !"".equals(sn.trim())){
				  	    terminalService.terminalAllotRecallBySN(null, merchant, null);
	    			}
	    		}
	    	}
			addActionError(context);
	    }
	    catch (ServiceException e){
	    	logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
	    }
		return SUCCESS;
	}
	
	private void org(){
		try{
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			orgList=orgService.listOrgs(logingOperators);
			getRequest().setAttribute("orgList", orgList);
			Map<String,String> brandMap=ConfigProperties.getPOSBrand();
			Map<String,String> nameMap=ConfigProperties.getPOSName();
			Map<String,String> typeMap=ConfigProperties.getPOSType();
			getRequest().setAttribute("brandMap", brandMap);
			getRequest().setAttribute("nameMap", nameMap);
			getRequest().setAttribute("typeMap", typeMap);
			//加载角色类型 
			Map roleMap=new HashMap();
			if(logingOperators.getRoleType().equals(Role.AGENT.getCode())){
				roleMap.put(Role.AGENT.getCode(),Role.AGENT.getName());
			}else{
				roleMap.put(Role.O_MANAGER.getCode(),Role.O_MANAGER.getName());
				roleMap.put(Role.AGENT.getCode(),Role.AGENT.getName());
			}
			getRequest().setAttribute("roleMap",roleMap);
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);				
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_TERMINAL_SN_EXCHANGE, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TermianlAllotRecallSearchCondition)getSession().getAttribute(SEARCH_SESSION_TERMINAL_SN_EXCHANGE);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
    
}
